package top.kaoshanji.ch12.threads;

import java.util.Arrays;

/**
 * author kaoshanji
 * ^_^
 * create time 2024/11/29 10:15
 */
public class Bank {

    // 每个数组元素都是一个账号
    private final double[] accounts;

    public Bank(int n, double initialBalance) {
        accounts = new double[n];

        // 这个是初始化数组的好方法啊，还专门看过文档来着
        Arrays.fill(accounts, initialBalance);
    }

    /**
     * 转账
     * @param from 来源账号
     * @param to 目标账号
     * @param amount 转账金额
     */
    public void transfer(int from, int to, double amount) {
        if (accounts[from] < amount) return;

        System.out.print(Thread.currentThread());
        accounts[from] -= amount;
        System.out.printf(" %10.2f from %d to %d", amount, from, to);
        accounts[to] += amount;
        System.out.printf(" Total Balance: %10.2f%n", getTotalBalance());

    }

    public double getTotalBalance() {
        double sum = 0;
        for (double a: accounts) {
            sum += a;
        }
        return sum;
    }

    public int size() {
        return accounts.length;
    }


}
